package ar.com.solidussource.howmuchmobile.services;

import ar.com.solidussource.howmuchmobile.common.entities.Market;
import ar.com.solidussource.howmuchmobile.common.exception.ServiceException;
import ar.com.solidussource.howmuchmobile.services.helper.RestServiceEntityExtractorHelper;
import ar.com.solidussource.howmuchmobile.services.helper.RestServiceHelper;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: FT31270775
 * Date: 31/10/12
 * Time: 17:41
 * To change this template use File | Settings | File Templates.
 */
public class MarketRestService implements RestService {
    private static String SERVICE_ENDPOINT = SERVER_ENDPOINT+"/market";
    private static String OP_LIST_ENDPOINT = SERVICE_ENDPOINT+"/list.json";

    public List<Market> getMarkets(int pageNumber, int size) throws ServiceException {
        List<Market> result;

        HttpClient httpClient = new DefaultHttpClient();

        HashMap<String, Object> params = new HashMap<String, Object>();

        params.put("pageNumber", pageNumber);
        params.put("size", size);

        String url = RestServiceHelper.addParamToUrl(OP_LIST_ENDPOINT, params);

        HttpGet get = new HttpGet(url);

        try{
            HttpResponse resp = httpClient.execute(get);
            String respStr = EntityUtils.toString(resp.getEntity());
            result = getMarkets(respStr);

        } catch (Exception e) {
            throw new ServiceException(e);
        }

        return result;
    }

    private List<Market> getMarkets(String jsonData) throws JSONException {
        RestServiceEntityExtractorHelper helper = new RestServiceEntityExtractorHelper();

        List<Market> markets = new ArrayList<Market>();

        JSONArray respJSON = new JSONArray(jsonData);

        for(int i=0; i<respJSON.length(); i++) {
            JSONObject marketJSON = respJSON.getJSONObject(i);

            markets.add(helper.getMarket(marketJSON));
        }

        return markets;
    }

}
